<!--
宠物喂食器设置页面
传入喂食器id，获取到喂食器的设置信息
{
'action':'setup',
'data':[{'time':'hh:mm:ss', 'times':2},'{time':'hh:mm:ss', 'time':1}]
}

-->
<script setup>
import {ref} from 'vue';
import { defineProps, onMounted } from 'vue';
import { IotApi } from '../js/apis';
import HeaderBar from '../components/HeaderBar.vue';
import * as atom from '../js/atom';
import FeederTimeEditor from '../components/FeederTimeEditor.vue';
import router from '../router';
import history_img_url from '../assets/history.png'

const params = defineProps({
    device_id: String, 
    title: String
});

const show_editor = ref(false);
const feeder_settings = ref([]);
const device_title = ref(params.title)

var current_index = -1;

onMounted(()=>{
    IotApi.get_feeder_setting(params.device_id).then(
        function fulfilled(settings){
            feeder_settings.value = settings;
        },
        function rejected(error){
            alert(error);
        }

    ).catch(function onrejected(reason){
        alert(reason);
    });
});


const show_feeding_record=()=>{
    router.push({
        name:'feeding_record',
        params:{device_id: params.device_id}
    })
    return true;
}

const do_edit_name=()=>{
    const new_title = prompt('请输入新的设备名', device_title.value)
    if(atom.okstr(new_title)){
        IotApi.modify_device_name(params.device_id, new_title).then((ret)=>{
            if (ret.code==0){
                device_title.value = new_title
            }else{
                alert(ret.msg)
            }
        }, (reason)=>{
            alert(reason)
        }).catch((reason)=>{
            alert(reason)
        });
    }
}

const add_click=()=>{
    current_index = -1;
    show_editor.value = true;
}

const on_feeder_time_get=()=>{
    if(current_index>=0){
        const setting = feeder_settings.value[current_index]
        return setting;
    }else{
        return {'time': atom.fmt_time(new Date(), 'hh:nn'), 'set':1};
    }
    
}

const on_feeder_time_set=(time, set, canceled)=>{
    if(canceled){
        show_editor.value = false;
        return;
    }
    if(!atom.okstr(time)){
        alert('时间不能为空！');
        return false
    }
    if (!atom.is_time_str(time)) {
        alert('时间格式错误，请输入正确的时间格式！');
        return false;
    }
    if(current_index>=0){
        //修改模式
        if(get_setting_index(time, current_index)>=0){
            alert(`喂食时间${time}已经存在！`);
            return false;
        }
    }else{
        //新增模式
        if(get_setting_index(time)>=0){
            alert(`喂食时间${time}已经存在！`);
            return false;
        }
    }

    if(set==undefined || set<=0){
        alert('喂食次数应大于0');
        return false;
    }
    var data = JSON.parse(JSON.stringify(feeder_settings.value));

    if(current_index==-1){
        data.push({'time':time, 'set': set});
    }else{
        data[current_index]={'time':time, 'set': set};
    }
    data.sort((a, b)=>atom.cmpstr(a.time, b.time));//按时间排序
    IotApi.send_msg(params.device_id, 'setting', data).then((value)=>{
        if(value.code==0){
            //更新值
            feeder_settings.value = data;
            //关闭编辑框
            show_editor.value = false;
        }
    },(reason)=>{
        alert(reason);
    }).catch((reason)=>{
        alert(reason);
    })

    show_editor.value = false;
}

const get_setting_index=(key, skip)=>{
    for(var index =0; index< feeder_settings.value.length; index++){
        if(index==skip){
            continue;
        }
        if(key===feeder_settings.value[index].time){
            return index
        }
    }
    return -1;
}


const do_edit=(key)=>{
    current_index = get_setting_index(key);
    show_editor.value = true;
}


const do_delete=(key)=>{
    current_index = get_setting_index(key);
    var data = JSON.parse(JSON.stringify(feeder_settings.value));
    data.pop(current_index);
    IotApi.send_msg(params.device_id, 'setting', data).then((value)=>{
        if(value.code==0){
            //更新值
            feeder_settings.value = data;
        }
    },(reason)=>{
        alert(reason);
    }).catch((reason)=>{
        alert(reason);
    })
}

const do_feed=()=>{
    IotApi.feed(params.device_id);
}

</script>

<template>
<div class="client-div">
    <div class="width100">
        <HeaderBar :title="device_title" :back=true :icon_url="history_img_url" :icon_callback="show_feeding_record"></HeaderBar>
    </div>
    <div class="item-width">
        <FeederTimeEditor v-if="show_editor" :setter="on_feeder_time_set" :getter="on_feeder_time_get"></FeederTimeEditor>
    </div>
    <div>
        <img class="large-img" src="../assets/cat_feeder.png" @click="do_edit_name">
    </div>
    <div>
        <button class="ok-btn" @click="do_feed">出粮</button>
    </div>

    <table>
        <tr v-for="item in feeder_settings" :key="item.time">
            <td>
                <div>
                    {{ item.time }}
                </div>
            </td>
            <td>
                <div>出粮{{ item.set }}份</div>
            </td>
            <td>
                <img class="item-img" src="../assets/edit.png" @click="do_edit(item.time)">
            </td>
            <td>
                <img class="item-img" src="../assets/delete.png" @click="do_delete(item.time)">
            </td>
        </tr>
    </table>
    <div>
        <img class="add-img" src="../assets/add.png" @click="add_click">
    </div>
</div>
</template>

<style scoped>
.client-div{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
    width: 100%;
    height: 100%;
}

.width100{
    width: 100%;
}

table{
    margin-top: 1rem;
    width: 100%;
    font-size: small;
}

tr{
    height: 2rem;
}
.large-img{
    width: 4rem;
    height: 4rem;
    padding-top: 1rem;
    padding-bottom: 1rem;
}
.item-img{
    width: 1rem;
    height: 1rem;
}
.add-img{
    width: 1.5rem;
    height: 1.5rem;
    margin-top: 1rem;
}
</style>